import { Effect } from 'dva';
import { Reducer } from 'redux';
import { queryCurrent } from '@/services/user';

interface UserModelState {
  currentUser?: any;
}

interface UserModelType {
  namespace: 'user';
  state: UserModelState;
  effects: {
    fetchCurrent: Effect;
  };
  reducers: {
    saveCurrentUser: Reducer<UserModelState>;
  };
}

const UserModel: UserModelType = {
  namespace: 'user',
  state: {
    currentUser: {},
  },
  effects: {
    *fetchCurrent({ callback }, { call, put }) {
      const user = yield call(queryCurrent);
      yield put({
        type: 'saveCurrentUser',
        payload: { ...user }
      });
      if (callback) callback(user);
    }
  },
  reducers: {
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: action.payload,
      };
    },
  }
};

export default UserModel;
